﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using NetTaste;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using static Dm.parser.LVal;

namespace DFGK_WMS.Repository
{
    public class TDictItemRepository : BaseRepository<TDictItem>, ITDictItemRepository
    {
        public TDictItemRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }

        /// <summary>
        /// 添加字典项
        /// </summary>
        /// <param name="dictItem"></param>
        /// <returns></returns>
        public bool AddTDictItem(TDictItem dictItem,out string message)
        {
            try
            {
                //string code = "DictItem";
                //var aobj = Context.TDictItems.AsNoTracking().Where(x => x.ItemCode.Contains(code)).OrderByDescending(x => x.CreateDate).FirstOrDefault();
                //if (aobj != null)
                //{
                //    string pattern = @"\d+";
                //    MatchCollection matches = Regex.Matches(aobj.ItemCode, pattern);
                //    string value = matches[matches.Count - 1].Value;
                //    int values = Convert.ToInt32(value);
                //    values++;
                //    dictItem.ItemCode = code + values.ToString("D4");
                //}
                //else
                //{
                //    int i = 1;
                //    dictItem.ItemCode = code + i.ToString("D4");
                //}
                message = "";
                var dictyitemcode = Context.TDictItems.AsNoTracking().FirstOrDefault(x => x.ItemCode == dictItem.ItemCode);
                if(dictyitemcode!=null)
                {
                    message = "项编码已存在！";
                    return false;
                }
                //查询所属字典类型
                var dictypeobj = Context.TDictTypes.Find(dictItem.TypeId);
                if(dictypeobj!=null)
                {
                    dictItem.TypeCode = dictypeobj.TypeCode;
                }
                dictItem.CreateDate = DateTime.Now;
                Context.TDictItems.Add(dictItem);
                //Context.SaveChanges();
                //dictItem.ItemCode = "DictItem" + dictItem.Id.ToString();
                //Context.Update(dictItem);
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {

                throw;
            }

        }

        public bool DelTDictItem(int id)
        {
            try
            {
                var dic = Context.TDictItems.Find(id);
                if (dic is not null)
                {
                    Context.TDictItems.Remove(dic);
                    return Context.SaveChanges() > 0;
                }
                return false;
            }
            catch (Exception)
            {

                throw;
            }
  
        }
        public List<TDictItem> GetDictItems()
        {
            return Context.TDictItems.AsNoTracking().ToList();
        }
        /// <summary>
        /// 字典树显示
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="typeId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<GetTDicItemDto> GetAllTDictItem(string? keyword, int typeId ,int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                var dicList = Context.TDictItems.Where(c=>c.TypeId==typeId).AsQueryable();
                if (!string.IsNullOrEmpty(keyword))
                {
                    dicList = dicList.Where(c => c.ItemName.Contains(keyword));
                }
                totalCount = dicList.Count();
                dicList = dicList.OrderBy(x => x.DisplayOrder).Skip((pageIndex - 1) * pageSize).Take(pageSize);
                if (dicList == null || dicList.Count() <= 0)
                {
                    return new List<GetTDicItemDto>();
                }
                return dicList.ToList().Select(d => new GetTDicItemDto()
                {
                    Id = d.Id,
                    TypeId = d.TypeId,
                    TypeName = Context.TDictTypes.Where(c=>c.Id==d.TypeId).FirstOrDefault()!=null ? Context.TDictTypes.Where(c => c.Id == d.TypeId).FirstOrDefault().TypeName : "",
                    ItemName = d.ItemName,
                    ItemCode = d.ItemCode,
                    ItemValue = d.ItemValue,
                    ParentId = d.ParentId,
                    LevelIndex = d.LevelIndex,
                    Remark = d.Remark,
                    DisplayOrder = d.DisplayOrder,
                    CreateDate = d.CreateDate,
                    CreateUserId = d.CreateUserId,
                    CreateUserName = d.CreateUserName,
                    ModifyDate = d.ModifyDate,
                    ModifyUserId = d.ModifyUserId,
                    ModifyUserName = d.ModifyUserName,
                    IsEnd = d.IsEnd,
                    TypeCode = d.TypeCode,
                    IsDefault = d.IsDefault,
                }).ToList();
            }
            catch (Exception)
            {

                throw;
            }
     
        }

        public List<GetTDicItemDto> GetTDictItemByDicTypeId(int dictypeId, int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                var dicList = Context.TDictItems.Where(c => c.TypeId == dictypeId).AsQueryable();
                totalCount = dicList.Count();
                dicList = dicList.OrderBy(x => x.DisplayOrder).Skip((pageIndex - 1) * pageSize).Take(pageSize);
                return dicList.ToList().Select(d => new GetTDicItemDto()
                {
                    Id = d.Id,
                    TypeId = d.TypeId,
                    TypeName = Context.TDictTypes.Where(c => c.Id == d.TypeId).First().TypeName,
                    ItemName = d.ItemName,
                    ItemCode = d.ItemCode,
                    ItemValue = d.ItemValue,
                    ParentId = d.ParentId,
                    LevelIndex = d.LevelIndex,
                    Remark = d.Remark,
                    DisplayOrder = d.DisplayOrder,
                    CreateDate = d.CreateDate,
                    CreateUserId = d.CreateUserId,
                    CreateUserName = d.CreateUserName,
                    ModifyDate = d.ModifyDate,
                    ModifyUserId = d.ModifyUserId,
                    ModifyUserName = d.ModifyUserName,
                    IsEnd = d.IsEnd,
                    TypeCode = d.TypeCode,
                    IsDefault = d.IsDefault,
                }).ToList();
            }
            catch (Exception)
            {

                throw;
            }
 
        }

        public TDictItem GetTDictItemById(int id)
        {
            try
            {
                return Context.TDictItems.Find(id);
            }
            catch (Exception)
            {

                throw;
            }

        }

        public List<TDictItemDto> GetTDictItemTreeByitemName(string? itemName,int typeId)
        {
            try
            {
                var res = Context.TDictItems.Where(a=>a.TypeId==typeId).AsQueryable();
                if (!string.IsNullOrEmpty(itemName))
                {
                    res = res.Where(x => x.ItemName.Contains(itemName));
                }
                return BuildTree(res, 0);
            }
            catch (Exception)
            {
                throw;
            }
        }
        private static List<TDictItemDto> BuildTree(IQueryable<TDictItem> items, int parentId)
        {
            try
            {
                return items.ToList().Where(x => x.ParentId == parentId).Select(x => new TDictItemDto
                {
                    Id = x.Id,
                    TypeId=x.TypeId,
                    ItemName = x.ItemName,
                    ParentId = x.ParentId,
                    ItemCode = x.ItemCode,
                    CreateDate = x.CreateDate,
                    CreateUserId=x.CreateUserId,
                    CreateUserName=x.CreateUserName,
                    Children = BuildTree(items, x.Id)
                }).ToList();
            }
            catch (Exception)
            {

                throw;
            }
           
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dictItem"></param>
        /// <returns></returns>
        public bool UpdTDictItem(TDictItem dictItem,out string message)
        {
            try
            {
                message = "";
                var dictitemobj = Context.TDictItems.AsNoTracking().FirstOrDefault(x => x.Id != dictItem.Id && x.ItemCode == dictItem.ItemCode);
                if (dictitemobj != null)
                {
                    message = "编码已存在！";
                    return false;
                }
                var dictypeobj = Context.TDictTypes.Find(dictItem.TypeId);
                if (dictypeobj != null)
                {
                    dictItem.TypeCode = dictypeobj.TypeCode;
                }
                dictItem.ModifyDate = DateTime.Now;
                Context.TDictItems.Update(dictItem);
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {

                throw;
            }

        }

        /// <summary>
        /// 字典项树形显示
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<MenuDto> GetMenuLists(int pageIndex, int pageSize, out int totalCount, int typeid, string name)
        {
            var dicitem = Context.TDictItems.Where(c => c.TypeId == typeid).AsQueryable();
            if (!string.IsNullOrEmpty(name))
            {
                dicitem = dicitem.Where(x => x.ItemName.Contains(name));
            }
            if(dicitem.Any())
            {
                dicitem = dicitem.OrderBy(x => x.ParentId);
                var mmlist = dicitem.FirstOrDefault();
                var list = GetMenuLists(dicitem.ToList(), mmlist.ParentId.GetValueOrDefault());
                totalCount = list.Count;
                list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                return list;
            }
            var list2 = GetMenuLists(dicitem.ToList(), 0);
            totalCount=list2.Count;
            list2 = list2.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return list2;
        }

        public static List<MenuDto> GetMenuLists(List<TDictItem> list, int pid)
        {
            return list.Where(x => x.ParentId == pid).Select(x => new MenuDto
            {
                id = x.Id,
                ParentId = x.ParentId,
                Meta = new MetaDto
                {
                    MenuName = x.ItemName,
                    MenuIcon = x.ItemCode,
                }, 
                CreateUserName = x.CreateUserName,
                DisplayOrder = x.DisplayOrder,
                children = GetMenuLists(list, x.Id)
            }).OrderBy(x => x.DisplayOrder).ToList();
        }
    }
}
